<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测仪器管理
 */
namespace app\admin\service;

use app\common\model\ChargingModel;
use app\common\model\DetectionModel;
use app\common\model\InstrumentModel;
use app\common\model\OrderModel;
use app\common\model\OrderProjectModel;
use app\common\model\ProjectModel;
use app\common\model\UserModel;
use think\Db;

class OrderService
{
    protected static $model;
    protected static $userModel;        // 用户 model
    protected static $projectModel;     // 项目 model
    protected static $instrumentModel;  // 仪器 model
    protected static $chargeModel;      // 充电桩 model
    protected static $orderProjectModel;  // 工单项目
    protected static $detectionModel; //检测数据 model

    /**
     * InstrumentService constructor.
     * @param OrderModel $orderModel
     * @author zws
     */

    public function __construct(
        OrderModel $orderModel,
        UserModel $userModel,
        ProjectModel $projectModel,
        InstrumentModel $instrumentModel,
        ChargingModel $chargingModel,
        OrderProjectModel $orderProjectModel,
        DetectionModel $detectionModel
    )
    {
        self::$model = $orderModel;
        self::$userModel = $userModel;
        self::$projectModel = $projectModel;
        self::$instrumentModel = $instrumentModel;
        self::$chargeModel = $chargingModel;
        self::$orderProjectModel = $orderProjectModel;
        self::$detectionModel = $detectionModel;
    }

    /**
     * 工单列表
     * @param $param
     * @return array|\PDOStatement|string|\think\Collection
     * @author zws
     */
    public function index($param)
    {
        if(!isset($param['page']) || empty($param['page'])){
            $param['page'] = 1;
        }
        if(!isset($param['limit']) || empty($param['limit'])){
            $param['limit'] = 10;
        }
        $where = [['is_del', '=', 1]];

        if (!empty($param['name'])) {
            $where = array_merge($where, [['name', 'like', '%'. $param['name'] . '%']]);
        }

        if (!empty($param['user_id'])) {
            $where = array_merge($where, [['user_id', '=', $param['user_id']]]);
        }

        // 获取总数
        $count = self::$model->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => $count];
        }

        // 查询工单列表
        $result = self::$model->where($where)
            ->page($param['page'], $param['limit'])
            ->order('id', 'asc')
            ->select();
        $result->map(function (&$item) {
            $item->user;
            $item->charge;
            $item->instrument;
            $item->orderParam;
            $item->orderImage;
            $item->orderProject;
            return $item;
        });
        $proportion = '0';
        // 计算百分比
        foreach($result as $key => $val) {

            if ($val->detection) {
                $detectionCount = count($val->orderProject->toArray());
                $successCount = self::$detectionModel->where('order_id', $val->id)->where('status', '>', 0)->count();

                $proportion = @round($successCount / $detectionCount, 2) * 100;
            }

            $result[$key]['proportion'] = is_nan($proportion) ? 0 : $proportion;
        }
        foreach ($result as $key => $val) {
            $result[$key]['status'] = intval($val['status']);
        }
        return ['data' => $result, 'count' => $count];
    }

    /**
     * 获取单个仪器数据
     * @param $param
     * @return array|null|\PDOStatement|string|\think\Model
     * @author zws
     */
    public function edit($param){
        if(empty($param) || !isset($param['id']) || empty($param['id'])){
            app_fail(9997);//参数错误
        }
        $row = self::$model->where('id', '=', $param['id'])->find();
        if(!$row){
            app_fail(7999);
        }
        return $row;

    }

    /**
     * 工单添加
     * @param $param
     * @return bool
     * @author zws
     */
    public function add($param)
    {
        if(empty($param))
        {
            app_fail(9997);//参数错误
        }
        // 开启事物
        Db::startTrans();
        try{
            $order = self::$model->create([
                'name' => $param['name'],
                'charge_id' => $param['charge_id'],
                'user_id' => $param['user_id'],
                'status' => 0,
                'is_del' => 1,
                'instrument_id' => $param['instrument_id']
            ]);
            //插入工单项目
            $projectData = [];
            // 过滤掉顶级检测项目 id
            $project = self::$projectModel->where('pid', '=', 0)->whereIn('id', $param['project_id'])->column('id');
            $project_id = array_diff($param['project_id'], $project);
            foreach ($project_id as $key => $val) {
                $projectData[] = [
                    'order_id' => $order->id,
                    'project_id' => $val
                ];
            }
            self::$orderProjectModel->saveAll($projectData);
            Db::commit();
            return true;
        }catch (Exception $e){
           Db::rollback();
            app_fail(9899);//仪器编辑失败
        }
    }

    /**
     * 工单修改、删除
     * @param $param
     * @return bool
     * @author zws
     */
    public function update($param)
    {
        if(empty($param) || !isset($param['id']) || empty($param['id']))
        {
            app_fail(9997);//参数错误
        }
        $row = self::$model->where('id', '=', $param['id'])->find();

        if(empty($row))
        {
            app_fail(6999);//工单不存在
        }
        if($row['status'] > 0 && $row['row'] != 2)
        {
            app_fail(6998);//6998
        }
        Db::startTrans();
        try{
            self::$model->allowField(true)->save($param, ['id'=>$param['id']]);

            // 先删除掉工单的项目
            self::$orderProjectModel->where(['order_id' => $param['id']])->delete();
            //插入工单项目
            $projectData = [];
            // 过滤掉顶级检测项目 id
            $project = self::$projectModel->where('pid', '=', 0)->whereIn('id', $param['project_id'])->column('id');
            $project_id = array_diff($param['project_id'], $project);
            foreach ($project_id as $key => $val) {
                $projectData[] = [
                    'order_id' => $param['id'],
                    'project_id' => $val
                ];
            }
            self::$orderProjectModel->saveAll($projectData);
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            app_fail(9899);//工单编辑失败
        }
    }

    public function detail($param)
    {
        if(empty($param) || !isset($param['id']) || empty($param['id']))
        {
            app_fail(9997);//参数错误
        }
        $row = self::$model->where('id', '=', $param['id'])->find();
        if(empty($row))
        {
            app_fail(6999);//工单不存在
        }
        $row->orderParam;
        $row->orderImage;
        $detection = $row->detection;
        $detection->map(function (&$item) {
            $item->project_name = $item->project->project_name;
        });
        return $row;
    }

    /**
     * 获取工单属性列表值
     * User: zhouyao
     * Date: 2018/9/11
     * Time: 下午11:10
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderAttr($param)
    {
        // 人员列表
        $user = self::$userModel->where(['is_del' => 1, 'status' => 1])
            ->field(['user_name', 'id'])
            ->select();
        // 充电桩列表
        $charge = self::$chargeModel->where(['is_del' => 1])
            ->field(['id', 'charge_name'])
            ->select();
        // 仪器列表
        $instrument = self::$instrumentModel->where(['is_del' => 1])
            ->field(['id', 'instrument_num'])
            ->select();
        // 项目列表
        $project = self::$projectModel->where('is_del', '=', 1)
            ->where('pid', '=', 0)
            ->field(['project_name as label', 'id'])
            ->select();

        foreach ($project as $key => $val) {
            $val->children = self::$projectModel->where('is_del', '=', 1)
                ->where('pid', '=', $val->id)
                ->field(['project_name as label', 'id'])
                ->select();
        }

        return [
            'userData' => $user,
            'chargeData' => $charge,
            'instrumentData' => $instrument,
            'projectData' => $project
        ];
    }

    /**
     * 删除工单与工单项目
     * User: zhouyao
     * Date: 2018/9/12
     * Time: 下午11:14
     * @param $param
     * @throws \app\common\exception\AppException
     */
    public function delete($param)
    {
        if (empty($param)) {
            app_fail(9997);
        }

        try {
            // 编辑工单信息为已删除
            self::$model->save(['is_del' => 2], ['id' => $param['id']]);
            //删除工单项目表
            self::$orderProjectModel->where('order_id', '=', $param['id'])->delete();
        } catch (\Exception $e) {
            print_r($e->getMessage());
            die;
            app_fail(9998);
        }
    }

    /**
     * 获取检测项目数据
     * @author zws
     * @param $param
     * @return array
     */
    public function orderProject($param)
    {
        if(empty($param) || !isset($param['id']) || empty($param['id']))
        {
            app_fail(9997);//参数错误
        }
//        //检测数据
//        $detection = self::$detectionModel->where('order_id', '=', $param['id'])->select();
//        $project_id = [];
//        foreach ($detection as $v)
//        {
//            $project_id[] = $v->project_id;
//        }
//        //检测项目
//        $projectData = [];
//        if($project_id)
//        {
//            $project = self::$projectModel->where('id', 'in', implode(',', $project_id))
//                ->select();
//            foreach ($project as $v)
//            {
//                $projectData[$v->id] = $v;
//            }
//        }
//
//        $resultData = [];
//        foreach ($detection as $k=>$v)
//        {
//            $resultData[$k]['project_name'] = isset($projectData[$v->project_id]) ?
//                $projectData[$v->project_id]['project_name'] : '';
//            $resultData[$k]['create_time'] = $v->create_time;
//            $resultData[$k]['status'] = isset($detection_status[$v->status]) ?
//                $detection_status[$v->status] : '';
//        }
        $resultData = [];
        $detection_status = config("param_config.detection_status");
        // 查工单项目
        $orderProject = self::$orderProjectModel->where('order_id', $param['id'])->select();
        $project_id = $orderProject->column('project_id');

        $project = self::$projectModel->whereIn('id', $project_id)->column('project_name', 'id');
        foreach ($orderProject as $key => $val) {
            // 判断是否检测过该项目
            $detection = self::$detectionModel->where('project_id', $val->project_id)->where('order_id', $val->order_id)->find();
            $resultData[] = [
                'project_name' => $project[$val->project_id],
                'create_time' => empty($detection) ? $val->create_time : $detection->create_time,
                'status' => empty($detection) ? $detection_status[0] : $detection_status[$detection->status]
            ];
        }
        return $resultData;
    }

}